import fetch from 'isomorphic-unfetch';
import { 
  ACTIVE_MENU, 
  FETCH_TVS_REQUEST,
  FETCH_TVS_FAILURE,
  FETCH_TVS_SUCCESS,
} from './actionTypes';

// 菜单切换处理
export const activeMenus = (id) => {
  return {
    type: ACTIVE_MENU,
    id
  }
}

// 获取tv列表数据
export const fetchTvsRequest = (subreddit) => {
  return {
    type: FETCH_TVS_REQUEST,
    subreddit
  }
}

export const fetchTvsFailure = (subreddit) => {
  return {
    type: FETCH_TVS_FAILURE,
    subreddit
  }
}

export const fetchTvsSuccess = (subreddit, json) => {
  return {
    type: FETCH_TVS_SUCCESS,
    subreddit,
    lists: json
  }
}

export const fetchTvs = (subreddit) => {
  return function (dispatch) {
    dispatch(fetchTvsRequest(subreddit))
    setTimeout(() => {
      return fetch(`https://api.tvmaze.com/search/shows?q=${subreddit.menu}`).then(
        response => response.json(),
        error => console.log("There is an error", error)
      ).then(json => {
        console.log(json)
        dispatch(fetchTvsSuccess(subreddit, json))
      })
    }, 3000)
  }
}